package com.foxhorse.androidpractice.activity.webview;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.Toast;

import com.foxhorse.androidpractice.R;
import com.foxhorse.androidpractice.activity.BaseActivity;
import com.foxhorse.androidpractice.utils.Constant;

import java.io.File;
import java.util.Random;

/**
 * Created by fanyang on 2017/6/8.
 */

public class CameraWebViewActivity extends BaseActivity {
    private final static String TAG = "CameraWebViewActivity";
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private int currentapiVersion = android.os.Build.VERSION.SDK_INT;
    private Random random;
    private WebView webView;
    private Button callJS;
    private Uri imageUri;

    /**
     * 验证并申请权限
     *
     * @param activity
     */
    public static void verifyStoragePermissions(Activity activity) {
        int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(
                    activity,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
            );
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera_webview);
        webView = (WebView) findViewById(R.id.webview);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.loadUrl("file:///android_asset/CameraUse.html");
        webView.addJavascriptInterface(new JsInterface(this), "AndroidWebView");
        webView.setWebChromeClient(new WebChromeClient());
        callJS = (Button) findViewById(R.id.btn_calljs);
        callJS.setOnClickListener(v -> {
            String call = "javascript:showInfoFromJava('这是android原生调用js方法')";
            webView.loadUrl(call);
        });
        verifyStoragePermissions(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0x1 && resultCode == RESULT_OK) {
            final String absolutePath = Constant.CONTENT_PROVIDER_LOCAL_PATH + getAbsolutePath(context, data.getData());
            webView.loadUrl("javascript:setImage('" + absolutePath + "')");
            //如果版本低于Android7，可以直接使用下面这一句
            //webView.loadUrl("javascript:setImage('" + data.getData() + "')");
        } else if (requestCode == 0x2 && resultCode == RESULT_OK) {
            final String absolutePath = Constant.CONTENT_PROVIDER_LOCAL_PATH + getAbsolutePath(context, imageUri);
            if (currentapiVersion < 24) {
                webView.loadUrl("javascript:setImgCamera('" + absolutePath + "')");
            } else {
                webView.loadUrl("javascript:setImgCamera('" + imageUri + "')");
            }
        }
    }

    /**
     * 返回一个文件的绝对路径
     *
     * @param context
     * @param uri
     * @return
     */
    public String getAbsolutePath(final Context context, final Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri,
                    new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(
                            MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    private class JsInterface {
        private Context mContext;

        public JsInterface(Context context) {
            this.mContext = context;
        }

        @JavascriptInterface
        public void showInfoFromJs(String name) {
            Toast.makeText(mContext, name, Toast.LENGTH_SHORT).show();
        }

        @JavascriptInterface
        public void getPic() {
            Intent albumIntent = new Intent(Intent.ACTION_PICK, null);
            albumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
            startActivityForResult(albumIntent, 0x1);
        }

        @JavascriptInterface
        public void openCamera() {
            //该方法存在一个弊端，每次拍照都会创建一个文件，会造成文件冗余。
            //如果不给每个文件设置不同的名字，则在第二次拍照确认后，仍然显示第一次拍照的内容。
            //原因不确定，不知道是否是因为由于在html文件中加载显示，因为url一致，导致不刷新的缘故。
            random = new Random();
            String tmp = String.valueOf(random.nextInt(99999999) + 100000000);
            Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            //针对Android版本不同，分两种情况处理
            if (currentapiVersion < 24) {
                imageUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "image" + tmp + ".jpg"));
                openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            } else {
                File file = new File(Environment.getExternalStorageDirectory() + "/image" + tmp + ".jpg");
                //这里的"com.fileprovider"对应于AndroidManifest.xml文件中配置Procider的authorities属性
                imageUri = FileProvider.getUriForFile(context, "com.fileprovider", file);
                openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                openCameraIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            }
            startActivityForResult(openCameraIntent, 0x2);
        }
    }
}
